// index.js
// 获取应用实例
const app = getApp();
import {$await,Throttle} from '../../utils/util';
import {commonAPI,getUserInfo,debounce} from '../../api/common/index';
const CONFIG = require('../../config.js');
const request = require("../../utils/request");
import {indexAPI,loginAPI} from '../../api/public/index';
const QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
import {getTiming} from '../../api/timing/index'

var qqmapsdk;
Page({
	data: {
		room_id:'',
		imgUrl: 'https://images.weserv.nl/?url=' + CONFIG.imgUrlImg,
		musicObj: '',
		hotObj: '',
		hotTitle:'',
		scrollHeight:0,
		tagvideoData: {
			list:[]
		},
		tagvideoPage:1,
		tagvideoDataList:[],
		area: wx.getStorageSync('area') || "全国" ,
		chat:true,
		closeDownload: true,
		muted: true,
		activeCategoryId: 0,
		activeIndex: 0,
		src: ' ',
		imgStop: '../../images/stop-icon.png',
		imgLiving: '../../images/gif/index-gif.gif',
		metudIcon: '../../images/metod-icon.png',
		openIcon: '../../images/bo-icon.png',
		fmList: [
		],
		dsUrl:'',
		menuList: [{
				"src": "../../images/fm-icon.png",
				"name": "找电台",
				"url": '/pages/fmList/fmList',
			},
			{
				"src": "../../images/mall-icon.png",
				"name": "听见严选",
				"url": '',
			},
			{
				"src": "../../images/music-icon.png",
				"name": "音乐广场",
				"url": '/pages/salon/salon',
			},
			{
				"src": "../../images/sort-icon.png",
				"name": "排行榜", 
				"url": '/pages/hplist/hplist',
			},
			{
				"src": "../../images/act-icon.png",
				"name": "活动",
				"url": '/pages/activity/activity',
			},
		],
		menuLists:[],
		dataArr: '',
		rowObj: "",
		background: ['https://seefm.oss-cn-beijing.aliyuncs.com/image/c17.jpg', '/images/indexSelect.png',
			'/images/location.png'
		],
		liveList: [
		],
		brandObj: {
			
		},
		interval: 2000,
		duration: 500,
		currentIndex: 0,
	},
	// 事件处理函数
	bindtapBanner(e) {
		console.log(e.currentTarget.dataset)
		wx.navigateTo({
			url: '/pages/webview/webview?webURL=' + e.currentTarget.dataset.url,
		})
	},
	async getBanner(tagid) {
		let id = JSON.stringify(tagid)
		let [err, res] = await $await(indexAPI.tagbanner({
			area: this.data.area,
			tagid: id
		}))
		if (res) {
			this.setData({
				bannerList: res,
			})
		}
	},
	async access() {
		// let id = JSON.stringify(tagid) 
		let [err, res] = await $await(indexAPI.access({}))
		if (res) {
			console.log(res)
			for(let i=0; i<res.list.length; i++){
				if(res.list[i].title == '听见严选'){
					this.setData({
						dsUrl:res.list[i].href
					});
				}
			}
			this.setData({
				hotTitle:res.title,
				menuLists: res.list,
			})
		}
	},
	async getTagvideo(tagid) {
		this.setData({
			tagid : tagid
		})
		let id = JSON.stringify(this.data.tagid)
		let [err, res] = await $await(indexAPI.tagvideo({
			area: this.data.area,
			tagid: id,
			page:this.data.tagvideoPage,
			pageSize:10
		}))
		if (res) {
			this.data.tagvideoData.list.push(...res)
			this.setData({
				['tagvideoData.list']: this.data.tagvideoData.list,
			})
			console.log(this.data.tagvideoData.list)
		}
	},
	onLaunch(){
		getApp().globalData.tabBarType = 'index';
	},
	
	onReady(res) {
		let _this = this;				
		_this.ctx = wx.createLivePlayerContext('player');
		_this.ctx.play({
			success: res => {
				console.log('播放成功')
			},
			fail: res => {
				console.log('播放失败，失败原因' + res.errMsg)
			}
		})
		if (this.data.option) return false
		wx.getLocation({
			type: 'gcj02',
			altitude: true,
			success: (res) => {
				var latitude = res.latitude // 经度
				var longitude = res.longitude // 纬度
				// 根据坐标调用 pointToAddress 方法
				_this.pointToAddress(latitude, longitude, function(address) {
					// 得到最终地址
					console.log(address);
					_this.setData({
						area: address
					})
					wx.setStorageSync('area', address)
					_this.init();
				})
			},
			fail(error) {
				wx.setStorageSync('area', "全国")
				_this.setData({
					area: "全国"
				})
				console.log('error')
				_this.init();
			}
		})
	},
	videoErrorCallback(e) {
	    console.log('视频错误信息:')
	    console.log(e.detail.errMsg)
	  },
	onLoad(option) {
		// getUserInfo()
		let area = 
		option.locationCity ? area = option.locationCity : area = wx.getStorageSync('area')
		if (option.locationCity) {
			this.setData({
				area,
				option: true
			})
			getTiming();
			this.init();
		}
		qqmapsdk = new QQMapWX({
			key: 'QOFBZ-4Q463-7L33D-3ARUM-H7PXO-VCFCF' // 开发密钥（key）必填
		});
		getTiming();
		wx.event.on('cb_room',(data)=>{
			data.forEach(item =>{
				if(item.action === 'switchStream'){
					this.switchStreamDate(item)
				}
			})
		})
	},
	/**
   * 生命周期函数--监听页面卸载
   */
	 async onUnload() {
    
  },
	/**
   * 生命周期函数--监听页面隐藏
   */
	 async onHide() {
		wx.event.off('cb_room')
		await wx.exit_room()
  },
	onShow() {
		let _this = this;
		// _this.init();
		wx.hideHomeButton();
		let liveData = this.data.live_data
		let room_id = (liveData && liveData.room_id) || ''
		wx.nextTick(()=>{
			setTimeout(() => {
				if(room_id && !wx.chatRoom){
					wx.join_room(room_id)
				}
			}, 1000)
		})
	},
	statechange(e) {
		console.log('live-player code:', e.detail.code)
	},
	error(e) {
		console.error('live-player error:', e.detail.errMsg)
	},
	// 事件处理函数
	loadClick() {
		console.log("dingwei");
		console.log(this.data.activeCategoryId);
		if (this.data.activeCategoryId == 0) {
			//跳转定位页
			wx.navigateTo({
				url: '/pages/selectCity/selectCity'
			})
		}
		this.setData({
			activeCategoryId: 0,
		});
	},
	async checkStatus(number) {
		let data = {number}
		let [err, res] = await $await(commonAPI.check(data));
		if (res.status==0 || res.live_number==0) {	
			wx.showToast({
			      title: '暂无直播',
			      icon: 'none',
			      duration: 2000,
			})
		}else{
			await wx.exit_room()
			let url = "/pages/channelLive/channelLive?number=" + number + ""
				wx.navigateTo({
					url
				})
		}
	},
	async liveData() { 
		let idx = this.data.activeIndex;
		let data = {
			type: 0,
			area: this.data.area,
		}
		let [err, res] = await $await(commonAPI.liveData(data));
		if (res) {
			let newArr= res.channel.map(i=>{ 
			    return {...i,isLived:true} 
			})
			this.setData({
				fmList: newArr,
			})		
			this.living(res.channel[idx].channel_id)
		}
	},
	async tabList(data) {
		let [err, res] = await $await(commonAPI.tabData(data));
		if (res) {
			this.setData({
				tabList: res,
			})
		}
	},
	async getMusic(data) {
		let [err, res] = await $await(commonAPI.getmusicvideo(data));
		if (res) {
			this.setData({
				musicObj: res,
			})
		}
	},
	async modSort(data) {
		let [err, res] = await $await(commonAPI.modsort(data));
		if (res) {
			this.setData({
				dataArr: res,
			})
			this.api();
			
		}
	},

	// async gueData(data) {
	// 	let [err, res] = await $await(commonAPI.guessdata(data));
	// 	if (res) {
	// 		this.setData({
	// 			['hotObj.list']: res.list,
	// 		})
	// 	}
	// },
	async getLive() {
		let data = {
			id: 3
		}
		let [err, res] = await $await(commonAPI.getlive(data));
		if (res) {
			this.setData({
				liveList: res.list,
			})
		}
	},
	async getAd() {
		let data = {
			id: 1,
			area: this.data.area
		}
		let [err, res] = await $await(commonAPI.getad(data))
		if (res) {
			this.setData({
				brandObj: res.list[0],
			})
		}
	},
	async init() {
		let _this = this;
		let area = this.data.area;
		let data = {
			area: area
		};
		_this.modSort(data);
		_this.liveData();
		_this.tabList(data);		
		// _this.gueData(data);
		_this.access();
		_this.getAd();
		
	},
	// 定义 pointToAddress 方法
	pointToAddress: function(latitude, longitude, callback) {
		var _this = this;
		qqmapsdk.reverseGeocoder({
			location: {
				latitude: latitude,
				longitude: longitude
			},
			success: function(res) {
				callback(res.result.address_component.city);
			},
			// fail: function(res) {console.log(res);},
			// complete: function(res) {console.log(res);}
		});
	},
	//定义接口方法
	api: function() { //modsort里取mod=video|vertical_channel|cross_channel|music的值
		let allList = [];
		let bigVideos=[];
		let music=[];
		let _this = this;
		let arr1 = _this.data.dataArr;
		let arr = arr1.filter((val, idx) => val.mod == 'vertical_channel' || val.mod == 'cross_channel')
		let bigVideo = arr1.filter((val, idx) => val.mod == 'video');
		let getmusic = arr1.filter((val, idx) => val.mod == 'music');
		{
			for (let i in arr) {
				let data = request.fetchRequest('/h5app/index/module/channels', {
					id: arr[i].id,
					module: arr[i].mod,
					city: this.data.area
				}, 'post')
				allList.push(data)
			}
			request.fetchRequestAll(allList).then(res => {
				let flierList = [];
				for (let i in res) {
					flierList.push(res[i].data.d);
				}
				_this.setData({
					flierList: flierList
				})
			})
		}
		{
			for (let i in bigVideo) {
				let data = request.fetchRequest('/h5app/index/guessdata', {
					id: bigVideo[i].id,
					module: bigVideo[i].mod,
					area: this.data.area
				}, 'post')
				bigVideos.push(data)
			}
			request.fetchRequestAll(bigVideos).then(res => {
				let flierList = [];
				for (let i in res) {
					flierList.push(res[i].data.d.list[0]);
				}
				_this.setData({
					['hotObj.list']: flierList,
				})
			})
		}
		{
			let dataes = {
				area: _this.data.area,
				id: getmusic[0].id,
				page: 1,
				pageSize: 10
			}
			_this.setData({
				musicId: getmusic[0].id,
			})	
			_this.getMusic(dataes);
			// for (let i in getmusic) {
			// 	let data = request.fetchRequest('/h5app/index/guessdata', {
			// 		id: bigVideo[i].id,
			// 		module: bigVideo[i].mod,
			// 		area: this.data.area
			// 	}, 'post')
			// 	bigVideos.push(data)
			// }
			// request.fetchRequestAll(bigVideos).then(res => {
			// 	let flierList = [];
			// 	for (let i in res) {
			// 		flierList.push(res[i].data.d.list[0]);
			// 	}
			// 	_this.setData({
			// 		['hotObj.list']: flierList,
			// 	})
			// })
		}
		
	},
	//直播流获取
	async living(id) {
		let data = {
			type: 1,
			channel_id: id,
		}
		if(wx.chatRoom){
			wx.exit_room()
		}
		let [err, res] = await $await(commonAPI.liveData(data));
		if (res) {
			this.setData({
				live_banner:res.live_data.banner,
				live_data: res.live_data.play,
				room_id:res.live_data.play.room_id
			})
			if(res.live_data.play.room_id){
				if(wx.$rong_success){
					wx.join_room(res.live_data.play.room_id)
				}else{
					const rongstatus = setInterval(() => {
						if(wx.$rong_success){
							wx.join_room(res.live_data.play.room_id)
							clearInterval(rongstatus)
						}
					}, 1000);
				}
			}
			console.log(res)
		}
	},
	goLive() {
		if (this.data.live_data.number) {
			this.checkStatus(this.data.live_data.number);			
		}
	},
	toWeb(e){
		let cont = e.currentTarget.dataset.cont;
		if(cont.jump_type==1){
			wx.navigateTo({
				url: '/pages/webview/webview?webURL=' + cont.obj_url
			})
		}else if(cont.jump_type==2){
			this.checkStatus(cont.obj_id)
		}
		console.log(e.currentTarget.dataset.cont)
	},
	mutedTap() {
		this.stopTap()
	},	
	liveTap:debounce(function(e){
		let idx = this.data.activeIndex;
		let data = this.data.fmList;
		for(let i in data){
			data[i].isLived=data[idx].isLived;
		}
		this.setData({
			fmList:data,
			activeIndex: e.currentTarget.dataset.index,
		});
		this.living(e.currentTarget.id)
	},300),	
	stopTap(){
		let idx = this.data.activeIndex;
		let data = this.data.fmList;	
		data[idx].isLived=!data[idx].isLived;
		// console.log(data[idx].isLived)
		this.setData({
			fmList:data,
			muted:data[idx].isLived
		})
		console.log(this.data.muted)
	},
	goAd(e) {
		// console.log(e.detail.currentTarget.dataset);
		wx.navigateTo({
			url: '/pages/webview/webview?webURL=' + this.data.brandObj.url
		})
	},
	hotOpen(e){
		console.log(e.detail);
		if(e.detail){
			let idx = this.data.activeIndex;
			let data = this.data.fmList;	
			let mod = "fmList["+idx+"].isLived";
			this.setData({
				[mod]:true,
				muted:true
			})
		}
	},
	switchStreamDate(e){
		let tNumber=this.data.live_data.number;
		let stream = e.content;
		let live_url = 'live_data.live_url';
		let status = 'live_data.status';
		//type:1切视频 type:2切音频 type:3重新调接口
		if(stream.type==1 && stream.number==tNumber){
			this.setData({
				[status]:1,
			})			
		}else if(stream.type==2 && stream.number==tNumber){
			this.setData({
				[status]:2,
			})
		}else{
			this.living(stream.number);
		}	
	},
	// 弹窗关闭
	downloadStatus(e) {
		const {
			dataset: {
				status
			}
		} = e.target
		this.setData({
			closeDownload: status
		})
	},
	download() {
		wx.navigateTo({
			url: '/pages/webview/webview?webURL=http://channels.h5.cbct.cn/downloadPage',
		})
		this.setData({
			closeDownload: true
		})
	},
	tabClick(e) {
		let tabItem = e.currentTarget.dataset;
		if (tabItem.index == 0) {
			this.loadClick();
			return 
		}
		this.setData({
			activeCategoryId: tabItem.index,
			['tagvideoData.id'] : null,
			['tagvideoData.list'] : [],
			tagvideoPage:1,
		});
		this.getBanner(tabItem.content)
		this.getTagvideo(tabItem.content)
		
	},
	toActived(e) {
		let index = e.currentTarget.dataset.index;
		let menu = this.data.menuLists;
		let url = menu[index].href;
		let type = menu[index].ident;
		switch(type){
			case 'radio':
				url='/pages/fmList/fmList'
				break
			case 'shop':
				url="/pages/webview/webview?webURL="+encodeURIComponent(this.data.dsUrl+'&isToken='+wx.getStorageSync('userInfo').ds_token+'&oId='+wx.getStorageSync('userInfo').openid)
				break
			case 'ranking':
				url='/pages/hplist/hplist'
				break
			case 'activity':
				url='/pages/activity/activity'
				break
			case 'voice':
				url='/pages/salon/salon'
				break
		}
		
		// if (index == 1) {
		// 	wx.navigateTo({
		// 		url: "/pages/webview/webview?webURL="+encodeURIComponent(this.data.dsUrl+'&isToken='+wx.getStorageSync('userInfo').ds_token+'&oId='+wx.getStorageSync('userInfo').openid),
		// 	})
		// 	return
		// }
		wx.navigateTo({
			url: url
		})
	},
	onPageScroll:Throttle(function(res) {
		// console.log('触发了')
		this.setData({
			// ['hotObj.scrollTop']: res.scrollTop,
			scrollHeight:res.scrollTop,
			// ['tagvideoData.scrollTop']: res.scrollTop
		});
	},300),
	  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
		if (this.data.activeCategoryId == -1) {
			return ;
		}
		this.data.tagvideoPage+=1
		this.getTagvideo(this.data.tagid)
  },
})
